package eai.tp2.lpco.web.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import eai.tp2.lpco.database.User;
import eai.tp2.lpco.requests.IRequest;
import eai.tp2.lpco.web.beans.ErrorList;
import eai.tp2.lpco.web.beans.PersonalInfo;
import eai.tp2.lpco.web.beans.UserBean;

/**
 * Servlet implementation class DatabaseUser
 */
public class DatabaseUser extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DatabaseUser() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		String action = request.getParameter("do");
		if(action.equals("personal")) {
			UserBean user = (UserBean)session.getAttribute("user");
			if(user.isLogged()) {
				IRequest req = null;
				InitialContext ctx = null;
				try {
					ctx = new InitialContext();
					req = (IRequest) ctx.lookup("RequestBean/remote");			
				} catch (NamingException e) {			
					String error;
					error = "Error while lookup for RequestBean: \n"+e.getMessage();
					List<String> errors = new ArrayList<String>();
					errors.add(error);
					ErrorList list = new ErrorList();
					list.setErrorList(errors);		
					request.setAttribute("list", list);
					RequestDispatcher rd = request.getRequestDispatcher("error.jsp");
					rd.forward(request, response);	
				}
				User usr = req.getPersonalInfo(user.getUsername());
				PersonalInfo personInfo = new PersonalInfo();
				personInfo.setAddress(usr.getAddress());
				personInfo.setEmail(usr.getEmail());
				personInfo.setFullName(usr.getFullName());
				request.setAttribute("personInfo", personInfo);
				RequestDispatcher rd = request.getRequestDispatcher("personal_info.jsp");
				rd.forward(request, response);
			} else {
				String error;
				error = "You must be login.";
				List<String> errors = new ArrayList<String>();
				errors.add(error);
				ErrorList list = new ErrorList();
				list.setErrorList(errors);		
				request.setAttribute("list", list);
				RequestDispatcher rd = request.getRequestDispatcher("error.jsp");
				rd.forward(request, response);	
			}
		}
	}

}
